package com.yihaodian.common;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

public class Files {
	private static final Logger log = Logger.getLogger(Files.class);

	public static InputStream strAsInputStream(String str)
			throws UnsupportedEncodingException {
		InputStream is = new ByteArrayInputStream(str.getBytes("utf-8"));

		return is;
	}

	public static String readAsString(InputStream is) throws IOException {
		StringWriter writer = new StringWriter();
		IOUtils.copy(is, writer, "utf-8");
		String str = writer.toString();

		return str;
	}

	/**
	 * Copy from srcDir to destDir
	 * 
	 * Example: srcDir: /dir/name destDir: /dir2 The result will be /dir2/name
	 * 
	 * @param srcDir
	 * @param destDir
	 * @return
	 */
	public static boolean copy(String srcDir, String destDir) {
		boolean success = false;
		File src = new File(srcDir);
		if (!src.exists()) {
			log.error("File doesn't exist, " + srcDir);
			return false;
		}

		File dest = new File(destDir);
		if (!dest.exists()) {
			dest.mkdirs();
		}

		try {
			org.apache.commons.io.FileUtils.copyDirectory(src, dest);
			success = true;
		} catch (IOException e) {
			log.error("Copy failed, src: " + srcDir + ", dest: " + destDir);
		}

		return success;
	}

}
